package com.tianyuchan.exception.exception;

import com.tianyuchan.exception.enums.ExplicableErrorCode;

import java.util.StringJoiner;

/**
 * @Classname : BaseException
 * @Description : 通用异常
 * @Author : cty
 * @Date 2023/3/19 20:00
 */


public class BaseException extends RuntimeException {

    protected ExplicableErrorCode errorCode;

    protected Object[] args;

    /**
     * 构造器
     */
    public BaseException() {
    }

    public BaseException(ExplicableErrorCode errorCode) {
        this.errorCode = errorCode;
    }

    public BaseException(ExplicableErrorCode errorCode, Object... args) {
        this.errorCode = errorCode;
        this.args = args;
    }

    /**
     * 方法
     */
    public String getErrorCode() {
        return this.errorCode.getCode();
    }

    public String getErrorMsg() {
        return getLocalizedMessage();
    }


    @Override
    public String getLocalizedMessage() {
        if (this.errorCode == null) {
            return null;
        }
        return String.format(errorCode.getMsg(), this.args);
    }


    @Override
    public String toString() {
        return this.getClass().getName() + ": " +
                new StringJoiner(" , ")
                .add("ErrorCode=[" + this.errorCode + "]")
                .add("ErrorMsg=[" + getLocalizedMessage() + "]");
    }

    @Override
    public String getMessage() {
        return toString();
    }
}
